// src/utils/pay.js

import { createOrder, queryOrder } from "@/api/fortune";

/**
 * 通用支付方法
 * @param {Object} orderParams - 下单参数
 * @param {Function} onSuccess - 支付成功回调(orderNo)
 * @param {Function} onFail - 支付失败回调(errMsg)
 */
export async function commonPay(orderParams, onSuccess, onFail) {
  try {
    const { data } = await createOrder(orderParams);
    const { payUrl, orderNo } = data;
    if (!payUrl || !orderNo) throw new Error("生成支付订单失败");
    const baseUrl = "https://h5.aiagentcompute.com/#";
    let typeParam = orderParams.type ? `&type=${orderParams.type}` : "";
    typeParam += orderParams.index ? `&index=${orderParams.index}` : "";
    const redirectUrl = orderParams.redirect
      ? `${baseUrl}${orderParams.redirect}?orderNo=${orderNo}${typeParam}`
      : `${baseUrl}/pages/pay/index?orderNo=${orderNo}${typeParam}`;
    const encodedRedirectUrl = encodeURIComponent(redirectUrl);
    const separator = payUrl.includes("?") ? "&" : "?";
    const finalPayUrl = `${payUrl}${separator}redirect_url=${encodedRedirectUrl}`;
    console.log(finalPayUrl);

    window.location.href = finalPayUrl;
    if (onSuccess) onSuccess(orderNo);
  } catch (e) {
    if (onFail) onFail(e.message || "生成支付订单失败");
  }
}
